package com.lagou.wwyan.rpc.client;

import com.alibaba.fastjson.JSON;
import com.lagou.wwyan.rpc.bean.RpcRequest;
import com.lagou.wwyan.rpc.bean.RpcResponse;
import com.lagou.wwyan.rpc.handler.RPCClientHandler;
import com.lagou.wwyan.rpc.service.UserService;
import com.lagou.wwyan.rpc.sirealizer.JSONSerializer;
import com.lagou.wwyan.rpc.sirealizer.RpcDecoder;
import com.lagou.wwyan.rpc.sirealizer.RpcEncoder;
import com.lagou.wwyan.rpc.sirealizer.Serializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RPCBoot {
    private ExecutorService executorService ;
    private RPCClientHandler handler;
    private Serializer serializer;



    public void initClient() throws InterruptedException {
        this.executorService =  Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        this.handler = new RPCClientHandler();
        this.serializer = new JSONSerializer();
        //创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        //创建客户端启动器
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group)
            .channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                //这里是序列化
                pipeline.addLast(new RpcEncoder(RpcRequest.class, serializer))
                        .addLast(new RpcDecoder(RpcResponse.class,serializer))
                        .addLast(handler);
            }

        });
        bootstrap.connect("127.0.0.1",9999).sync();
    }
    @SuppressWarnings("unchecked")
    public <T>  T createProxy(Class<T> clazz){
        return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{clazz},new InvocationHandler() {
            public Object invoke(Object o, Method method, Object[] args) throws Throwable  {
                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setRequestId(UUID.randomUUID().toString());
                rpcRequest.setClassName(clazz.getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameters(args);
                if (args != null) {
                    Class<?>[] parameterTypes = new Class[args.length];
                    for (int i = 0; i < args.length; i++) {
                        Class<?> aClass = args[i].getClass();
                        parameterTypes[i] = aClass;
                    }
                    rpcRequest.setParameterTypes(parameterTypes);
                } else {
                    rpcRequest.setParameterTypes(new Class[0]);
                }

                RpcResponse response = executorService.submit(() -> handler.sendRequest(rpcRequest)).get();
                return response.getData();
//            return "success";
            }
        });
    }
}
